/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.mzk.lidovky.articles.importLogRestore;

import cz.mzk.lidovky.articles.PropertyNames;
import cz.mzk.rehan.commons.Dom4jUtils;
import cz.mzk.rehan.commons.PropertyLoader;
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.dom4j.Document;

/**
 *
 * @author Martin Řehánek <rehan at mzk.cz>
 */
public class ImportLogRestorer {

    private static final Logger logger = Logger.getLogger(ImportLogRestorer.class.getName());
    private static final String FOXML_SUFFIX = ".foxml";
    private static final String LOG_SUFFIX = ".xml";
    private final File logDir;
    private final ImportLogBuilder logBuilder;
    private final List<String> articlePidList;

    public ImportLogRestorer(PropertyLoader properties) {
        String risearchUrl = properties.loadString(PropertyNames.RISEARCH_URL);
        logBuilder = new ImportLogBuilder(risearchUrl);
        logDir = properties.loadFile(PropertyNames.IMPORT_LOG_DIR, false);
        if (!logDir.exists()) {
            logDir.mkdirs();
        }
        File foxmlDir = properties.loadDir(PropertyNames.IMPORT_FOXML_DIR);
        articlePidList = loadArticlePids(foxmlDir);

    }

    private List<String> loadArticlePids(File foxmlDir) {
        File[] foxmlFiles = foxmlDir.listFiles(new FilenameFilter() {

            @Override
            public boolean accept(File dir, String name) {
                return name.endsWith(FOXML_SUFFIX);
            }
        });
        List<String> result = new ArrayList<String>(foxmlFiles.length);
        for (File foxmlFile : foxmlFiles) {
            String filename = foxmlFile.getName();
            String pid = filename.substring(0, filename.length() - FOXML_SUFFIX.length());
            result.add(pid);
           // break;
        }
        return result;
    }

    public void restore() {
        for (String articlePid : articlePidList) {
            Document doc = logBuilder.createImportLog(articlePid);
            File logFile = buildLogFile(articlePid);
            Dom4jUtils.saveDocument(doc, logFile);
            logger.log(Level.INFO, "Import log for article {0} restored", articlePid);
        }
    }

    private File buildLogFile(String articlePid) {
        String fileName = logDir.getAbsolutePath() + File.separator
                + articlePid + LOG_SUFFIX;
        return new File(fileName);
    }
}
